<?php
/**
  * filecache.class.php
  * author konakona
  * date 2009/6/12
  * package libs
  * version 1.0.1
 */
class filecache {
    public static $cacheDir = null;
    public static $cacheTime =0;
    public static $DS;
    public static function get( $key ){
        if( self::cacheIsActive( $key ) )
            return @include self::getCacheFile( $key );
        else
            return FALSE;
    }
    public static function init( $cacheTime = 0 ){
        if( empty( self::$cacheDir ) )
            self::$cacheDir = m::$config['CACHE_DIR'];
        if($cacheTime!=0)
            self::$cacheTime = $cacheTime;
        self::$DS = DIRECTORY_SEPARATOR;
    }
    public static function getCacheFile( $key ){
        return self::$cacheDir.self::$DS.md5( $key ).'.cache.php';
    }
    public static function set( $key,$value ){
            return self::write( self::getCacheFile( $key ),'<?php return '.var_export( $value ,true ).';' );
    }
    /**
     * 缓存是否有效
     * @param string $key 键
     * @return bool
     */
    private static function cacheIsActive( $key ){
        if(!file_exists(self::$cacheDir))
            mkdir(self::$cacheDir);
        return file_exists( self::getCacheFile( $key ) )&&((filemtime( self::getCacheFile( $key ) )+self::$cacheTime) > time());
    }
    private static function write($file,$content,$mode='w') {
        if(!@$fp = @fopen($file, $mode)) {
			self::writeLog('cound not write file:'.$file,'m::write');
		    if($exit) { self::halt('cound not write file:'.$file); } else { return false;}
        } else {
            @flock($fp, 2);
		    @fwrite($fp, $content);
		    @fclose($fp);
            return true;
        }
    }
    /**
     * 清空过期文件
     */
    public static function clearDir() {
        $d = dir(self::$cacheDir);
        while (false !== ($entry = $d->read())) {
           if((substr($entry,-10)=='.cache.php')&&((filemtime( self::$cacheDir.self::$DS.$entry )+self::$cacheTime) < time())) {
               unlink(self::$cacheDir.self::$DS.$entry);
           }
        }

    }
}